package com.ecoolex.discount.sales.job.scheduler;

import com.ecoolex.discount.sales.core.manager.PaymentOrderManager;
import com.ecoolex.discount.sales.core.manager.PaymentOrderRecordManager;
import com.ecoolex.discount.sales.core.service.WeiXinPayService;
import com.ecoolex.discount.sales.entity.PaymentOrder;
import com.ecoolex.discount.sales.entity.PaymentOrderRecord;
import com.ecoolex.framework.scheduler.Job;
import com.ecoolex.framework.scheduler.JobComponent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Calendar;
import java.util.List;

/**
 * 支付订单检查
 */
@JobComponent
public class PaymentOrderCheckJob {

    private static final Logger log = LoggerFactory.getLogger(PaymentOrderCheckJob.class);

    @Autowired
    private PaymentOrderManager paymentOrderManager;
    @Autowired
    private PaymentOrderRecordManager paymentOrderRecordManager;
    @Autowired
    private WeiXinPayService weiXinPayService;

    @Job(name = "discount.sales.PaymentOrderCheckJob.checkPayStatus", describe = "检查支付订单的支付状态")
    public void checkPayStatus() {
        // 5秒的间隔查询时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, -5);
        List<PaymentOrder> orderList = paymentOrderManager.queryPayApplyTimeout(calendar.getTime(), 10);

        orderList.forEach(order -> {
            PaymentOrderRecord record = paymentOrderRecordManager.getLastPayApplyRecord(order.getPaymentOrderId());
            // 微信支付
            if (WeiXinPayService.PAYMENT_TYPE.equalsIgnoreCase(record.getPaymentType())) {
                weiXinPayService.checkPayStatus(order, this.getClass().getSimpleName());
            }
        });
    }

    @Job(name = "discount.sales.PaymentOrderCheckJob.checkRefundStatus", describe = "检查支付订单的退款状态")
    public void checkRefundStatus() {
        // 5秒的间隔查询时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, -5);
        List<PaymentOrder> orderList = paymentOrderManager.queryRefundApplyTimeout(calendar.getTime(), 10);

        orderList.forEach(order -> {
            // 微信支付
            if (WeiXinPayService.PAYMENT_TYPE.equalsIgnoreCase(order.getPaymentType())) {
                weiXinPayService.checkRefundStatus(order, this.getClass().getSimpleName());
            }
        });
    }
}
